// 主界面
;define(function(require, exports, module) {
    'use strict';
    var util = require("util");
    var base = require("base");
    var leftMenu = require("../leftMenu/leftMenu");
    var topMenu = require("../topMenu/topMenu");
    var router = require("../hash/pageRouter");
    var footer = require("../footer/footer_main");
    var dialog = require("dialog");
    var validate = require("validate");
    var constant = require("constant");
    var tools = require("tools");
    var firstVisited = 0;
    var auditState;
    var leftTime;
    var leftM;
    var pageIndex = 1,
        pageSize = 10,
        totalPageCount = 1,
        totalRecordCount = 0; //分页初始化
        
    var init = function(){
    	$("#header").html(require("../topMenu/topMenu.html"));
    	firstVisited = base.getUrlParam("firstVisited");
    	auditState = base.getUrlParam("auditState");
    	leftTime = base.getUrlParam("leftTime");
    	
    	tools.clearNoNumAll($(".table-search"));
    	
    	leftM = base.getUrlParam("leftM");
    	leftM = leftM == null?4:leftM;
    	footer.init();
    	$("#footer").removeClass("none");
		
    	leftMenu.init(leftM);
    	
    	$(".memberList").parent().parents("li").addClass("leftMenu-open");
    	$(".leftMenu-item").removeClass("leftMenu-active");
    	$(".memberList").addClass("leftMenu-active");
    	
    	topMenu.init(2);
    	$(".footer").removeClass("none");
    	
    	if (auditState != null) {
    		$("select[name=auditState]").val(auditState);
    	}
    	
    	if (leftTime != null) {
    		$("input[name=leftTime]").val(leftTime);
    	}
    	
    	tableInit();
    	getEnterpriseList();
		initEvent();
		router.init();
		
		if(firstVisited != 1){
			$(".table-section").removeClass("none");
		}
    };
    
    var html_delete = require("../client/clientManage_delete.html");
	var html_details = require("../client/clientManage_details.html");
	var initEvent = function(){
		//若未登录，则返回登陆页面
		if(base.getData("sid")==null||base.getData("sid")==""||base.getData("sid")==undefined){
			top.location.href="../login/login.html";
		}
		
		$(".memberGradeAduitList").unbind("click").click(function(){
			router.route("client/memberGradeaudit.html");
		});
    };
    
     //搜索按钮
    $(".table-search-button").on("click",function(){
        pageIndex = 1;
		pageSize = 10;
		totalPageCount = 1;
		totalRecordCount = 0; //分页初始化
        getEnterpriseList();
    });
    
    //删除企业
    var disableEnterprise = function(enterpriseIds){
    	var delete_clientManage_dialog = $("#delete_clientManage_dialog");
    	dialog.showDialog(delete_clientManage_dialog, function() {});
    	$(".footerBtn").on("click", "#sure_delete", function() {
    	base.fnAjax({
            action: "disableEnterprise.json",
            oData: {
            	enterpriseId: enterpriseIds
            }, //传递参数
            fnSuccess: function(data) {
                if (data.status == 200) {
                	dialog.hideDialog($("#delete_clientManage_dialog"));
                	getEnterpriseList();
                } else {
                    base.alert(2,"企业信息删除失败");
                }
            }
        });
    	});
    }
    
    // 冻结企业
	var freezeEnterprise1 = function(enterpriseId) {
		base.fnAjax({
			action: 'freezeEnterprise1.json',
			async: false,
			oData: {
				enterpriseId: enterpriseId
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.alert(1, "冻结成功！");
					location.href="../client/clientManage.html";
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};
	
	// 禁用企业
	var forbidEnterprise = function(enterpriseId) {
		base.fnAjax({
			action: 'forbidEnterprise.json',
			async: false,
			oData: {
				enterpriseId: enterpriseId
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.alert(1, "禁用成功！");
					location.href="../client/clientManage.html";
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};
	
	//tablesorter初始化
	var tableInit = function() {
		  $("#enterpriseListTable").tablesorter({
		    widthFixed: false,
			theme: 'blue',
			showProcessing: false,
			 tabIndex: true,
			 sortMultiSortKey: "shiftKey",
		    sortResetKey: 'ctrlKey',
			ignoreCase: true,
			sortForce: null,
			resort:false,
			headers:{
				 0: {sorter: false},
				 1: {sorter: false},
      			 2: {sorter: false},
      			 3: {sorter: false},
      			 4: {sorter: false},
      			 5: {sorter: false},
      			 6: {sorter: false},
      			 7: {sorter: false},
      			 8: {sorter: false},
      			 9: {sorter: false},
      			 10: {sorter: false},
      			 11: {sorter: false}
				},
			headerTemplate : '{content} {icon}',
			widgets: [ 'zebra', 'scroller' ],
			widgetOptions : {
		      scroller_height : 420,
		      // scroll tbody to top after sorting
		      scroller_upAfterSort: true,
		      // pop table header into view while scrolling up the page
		      scroller_jumpToHeader: true,
		      // In tablesorter v2.19.0 the scroll bar width is auto-detected
		      // add a value here to override the auto-detected setting
		      scroller_barWidth : null
		      // scroll_idPrefix was removed in v2.18.0
		      // scroller_idPrefix : 's_'
		    }
		  });
		  
			//事件
		  	$("#enterpriseListTable").bind("sortEnd",function(event) {
				var table = event.target;
				var columnSort       =  table.config.sortList[0][0];          									 //第几列排序，序号
				var columnSortName   =  $(table.config.headerList[table.config.sortList[0][0]]).text();          //第几列排序，名称
				var columnSortType   =  table.config.sortList[0][1];    	  									 //0:升序，1：降序
				//测试代码2：排序
			});
	};
	
	// 同步企业信息到仓储系统
	var syncCustInfo = function(enterpriseId) {
		base.fnAjax({
			action: 'syncCustInfo.json',
			async: false,
			oData: {
				enterpriseId: enterpriseId
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.alert(1, "同步成功！");
					location.href="../client/clientManage.html";
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};
	
	// 启用企业
	var enableEnterprise = function(enterpriseId) {
		base.fnAjax({
			action: 'enableEnterprise.json',
			async: false,
			oData: {
				enterpriseId: enterpriseId
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.alert(1, "启用成功！");
					location.href="../client/clientManage.html";
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};
    
    //获取企业用户列表
	var getEnterpriseList = function(){
		var body = base.parseForm($("#searchEnterprise"));
		body.createDateTimeBegin = body.createDateTimeBegin.split("-").join("");
		body.createDateTimeEnd = body.createDateTimeEnd.split("-").join("");
		
        base.fnAjax({
            action: "inquireEnterprisePageList.json",
            oData: {
            	enterpriseType: 0,
            	pageIndex: pageIndex,
                pageSize: pageSize,
                mobile:body.mobile,
                enterpriseName:body.enterpriseName,
                legalPerson:body.legalPerson,
                state:body.state,
                auditState:body.auditState,
                createDateTimeBegin:body.createDateTimeBegin,
                createDateTimeEnd:body.createDateTimeEnd,
                leftTime: body.leftTime,
                followPerson: body.followPerson,
                alreadyCreditStart: body.alreadyCreditStart,
                alreadyCreditEnd: body.alreadyCreditEnd,
                finalState: body.finalState
            }, //传递参数
            fnSuccess: function(data) {
                if (data.status == 200) {
                	
                	juicer.register("getValueByKey", constant.getValueByKey);
                	juicer.register("formatCurrency", tools.formatCurrency);
                	var tpl = $("#enterpriseListTpl").html();
                    var html = juicer(tpl, data);
                    $("#enterpriseListBody").html(html);
                    totalPageCount = data.totalPageCount;
                    totalRecordCount = data.totalRecordCount;
                    base.pageControl(
                    	$("#clientPagenation"),
                        totalRecordCount,
                        data.pageIndex,
                        data.pageSize,
                        function(p) {
                            pageIndex = p;
                            getEnterpriseList();
                    });
                    
                     //点击详情
                    $(".table_details_link").unbind("click").click(function(){
                    	router.route("client/clientManage_details.html?enterpriseId=" + $(this).parents("tr").attr("enterpriseId"));
                    });
			       
			            //点击删除
			        $("#enterpriseListBody").on("click",".table_delete_btn",function(){
			        	$("#popdialog").html(html_delete);
			           var enterpriseIds = [];
			           var $this = $(this).parents("tr.tr_style");
					   enterpriseIds.push($this.attr("enterpriseId"));
			           disableEnterprise(enterpriseIds);
			        });
			        
			        //禁用企业
					$(".table_forbidden_btn").unbind("click").click(function(){
						var $this = $(this);
						dialog.showConfirmDialog("禁用企业", "是否确定禁用该企业？", function(){
							forbidEnterprise($this.parents("tr").attr("enterpriseId"));
						});
					});
					
					//冻结企业
					$(".table_freeze_btn").unbind("click").click(function(){
						var $this = $(this);
						dialog.showConfirmDialog("冻结企业", "是否确定冻结该企业？", function(){
							freezeEnterprise1($this.parents("tr").attr("enterpriseId"));
						});
					});
					
					//启用企业
					$(".table_enable_btn").unbind("click").click(function(){
						var $this = $(this);
						dialog.showConfirmDialog("启用企业", "是否确定启用该企业？", function(){
							enableEnterprise($this.parents("tr").attr("enterpriseId"));
						});
					});
					
					//同步企业信息到仓储系统
					$(".table_sync_link").unbind("click").click(function(){
						var $this = $(this);
						dialog.showConfirmDialog("同步企业", "是否同步该企业到仓储系统？", function(){
							syncCustInfo($this.parents("tr").attr("enterpriseId"));
						});
					});
					
					tools.inquireCurrentOperationList($("#main"));
					$("#enterpriseListTable").trigger("update");
					
                } else {
                    base.alert(2,"信息获取失败");
                }
            }
		});
	};
	
    return {
        init:init
    };
});